//
//  ScrollViewAnimateProtocol.swift
//  CodingTest
//
//  Created by LYPC on 2021/11/18.
//

import UIKit
import MJRefresh

public protocol ScrollViewAnimateProtocol {
    
    var animateView: UIActivityIndicatorView  { get }
    var baseView: UIScrollView { get }
    
    func setAnimatingPosition(_ centerY: CGFloat)
    func startAnimating(at centerY: CGFloat)
    func startAnimating(at center: CGPoint?)
    func stopAnimating()
    var isAnimating: Bool { get }
    func endRefresh()
    func addEmpty(attrTip: NSAttributedString,
                  type: ScrollViewErrorType,
                  topY: CGFloat,
                  offsetY: CGFloat?,
                  callback: (() -> Void)?)
    func addError(attrTips: NSAttributedString,
                  topY: CGFloat,
                  offsetY: CGFloat?,
                  callback: (() -> Void)?)
}


public extension ScrollViewAnimateProtocol {
    
    func setAnimatingPosition(_ centerY: CGFloat) {
        animateView.snp.remakeConstraints { (m) in
            m.centerX.equalToSuperview()
            m.centerY.equalTo(centerY)
        }
    }
    func startAnimating(at centerY: CGFloat) {
        animateView.snp.remakeConstraints { (m) in
            m.centerX.equalToSuperview()
            m.centerY.equalTo(centerY)
        }
        animateView.superview?.bringSubviewToFront(animateView)
        animateView.startAnimating()
        baseView.isScrollEnabled = false
    }
    func startAnimating(at center: CGPoint? = nil) {
        if let center = center {
            animateView.snp.remakeConstraints { (m) in
                m.center.equalTo(center)
            }
        }
        animateView.superview?.bringSubviewToFront(animateView)
        animateView.startAnimating()
        baseView.isScrollEnabled = false
    }
    func stopAnimating() {
        animateView.stopAnimating()
        baseView.isScrollEnabled = true
    }
    var isAnimating: Bool {
        return animateView.isAnimating
    }
    func endRefresh() {
        baseView.mj_header?.endRefreshing()
        baseView.mj_footer?.endRefreshing()
    }
    
    func addEmpty(attrTip: NSAttributedString,
                  type: ScrollViewErrorType = .empty,
                  topY: CGFloat = 0,
                  offsetY: CGFloat? = nil,
                  callback: (() -> Void)? = nil) {
        baseView.setEmpty(type: type, tips: attrTip, callback: callback)
        if let offsetY = offsetY
        { baseView.placeEmpty(topY: topY, offsetY: offsetY) }
    }
    func addError(attrTips: NSAttributedString,
                  topY: CGFloat = 0,
                  offsetY: CGFloat? = nil,
                  callback: (() -> Void)? = nil) {
        baseView.setError(tips: attrTips, callback: callback)
        if let offsetY = offsetY { baseView.placeError(topY: topY, offsetY: offsetY) }
    }
}
